package components;

import java.math.BigInteger;
import java.security.InvalidParameterException;
import java.util.List;

import android.content.Context;
import data.RCDevice;
import data.SMSCommand;
import data.SendingSMSCommand;

public class SMSSendingCommandFactory {

	public static String createSMSCommandString(SMSCommand smsCommand) {
		return smsCommand.toString();
	}

	// public static SMSCommand createSMSCommandWithConfiguredPhone(
	// Context context, String subject, int deviceIndex, boolean isOn) {
	// String phoneNumber = SMSCommandManager.sharedPhoneNumber(context);
	//
	// if (phoneNumber == null) {
	// return null;
	// }
	//
	// SMSCommand sms = new SendingSMSCommand(phoneNumber, subject,
	// deviceIndex, isOn);
	//
	// return sms;
	// }

	/**
	 * 
	 * @param context
	 * @param cmd
	 * @param content
	 * @exception InvalidParameterException
	 * @return
	 */
	public static SMSCommand createSMSCommandWithConfiguredPhone(
			Context context, String cmd, String content) {
		String phoneNumber = SMSCommandManager.sharedPhoneNumber(context);

		if (phoneNumber == null) {
			return null;
		}

		String message = "";
		if (cmd.equalsIgnoreCase(SMSCommand.CMD_CODE_TURN_OFF_ALARM)) {
			message = alertDevicesToHexString(AlarmManager.sharedAlarmList(
					context).getDevices());
			message = SMSCommand.CMD_CODE_TURN_OFF_ALARM + message;
		} else if (cmd == SMSCommand.CMD_CODE_POWER) {
			message = cmd + "" + content;
		} else if (cmd.equalsIgnoreCase(SMSCommand.CMD_CODE_TURN_ON)) {
			message = cmd + "" + content;
		} else if (cmd.equalsIgnoreCase(SMSCommand.CMD_CODE_TURN_OFF)) {
			message = cmd + "" + content;
		} else if (cmd == SMSCommand.CMD_TEST) {
			message = cmd + "" + content;
		} else if (cmd == SMSCommand.CMD_RESULT) {
			message = cmd + "" + content;
		} else if (cmd.equalsIgnoreCase(SMSCommand.CMD_CODE_UPDATE)) {
			message = cmd;
		} else {
			message = cmd + " " + content;
		}
		SMSCommand sms = new SMSCommand(phoneNumber, message);

		return sms;
	}

	private static String alertDevicesToHexString(List<RCDevice> devices) {
		long result = 0;

		for (RCDevice rcDevice : devices) {
			if (rcDevice.isAlert()) {
				result = result | (1 << rcDevice.getDeviceIndex());
			}
		}

		String numberString = String.valueOf(result);

		return new BigInteger(numberString, 10).toString(16);
	}

	private static String devicesToHexString(List<RCDevice> devices) {
		long result = 0;

		for (RCDevice rcDevice : devices) {
			if (rcDevice.isOn()) {
				result = result | (1 << rcDevice.getDeviceIndex());
			}
		}

		String numberString = String.valueOf(result);

		return new BigInteger(numberString, 10).toString(16);
	}
}
